import yapdi
import threading, time
import sys, os
from django.core.management import setup_environ
from ticketquest import settings
setup_environ(settings)
from ticketer.models import Ticket, Comment
from ticketer.lib import tqdlib

"""
    This command is a daemon starter.  The daemon will listen for mail
    and intercept mail to the supplied ticket mail address found in the configuration.
"""

daemon = yapdi.Daemon(pidfile='/var/run/tqddaemon.pid')

parser = tqdlib.Parser()
parser.mailfetcher.login()
args = sys.argv
    
#if 'start' in args:
#    retcode = daemon.daemonize()
#    parser.logger.info("Daemonizer called. %s : %s" % (retcode, yapdi.OPERATION_SUCCESSFUL))
#    if retcode == yapdi.OPERATION_SUCCESSFUL:
#        parser.logger.info("Daemon Started: %s pid." % daemon.pidfile)
#    else:
#        parser.logger.error("Daemon Failure!")
#        sys.exit()
#else:
#    parser.logger.info("Attempting to stop the daemon at pid: %s" % daemon.pidfile)    
#    pid = open('/var/run/tqddaemon.pid', 'r').readline()
#    os.system("kill -9 %s" % pid)
#    parser.logger.info("Daemon killed successfully.")
#    os.system('rm /var/run/tqddaemon.pid')
#    sys.exit(0)
        
while 1:
    parser.emailrecords = parser.mailfetcher.fetch()
    #mailkiller_thread = threading.Thread(target=parser.mailfetcher.purge())
    if len(parser.emailrecords.keys()) > 0:
        parser.logger.info("Records exists, computing.")
        for record in parser.emailrecords:
            parser.parse_email(record)
        parser.emailrecords = {}
        #collected = gc.collect()
        #db.reset_queries()
        #parser.logger.info("Garbage collection run started: (%d) objects collected." % collected)
    #    if not mailkiller_thread.is_alive():
    #        mailkiller_thread.start()
    else:
        parser.logger.info("Sleeping")
        time.sleep(5) 
  
        
